<template>
  <div class="hello" :updateStatusData="updateStatusData" style="width:100%;height:700px;"  >
    <!--<div id="editor" type="text/plain" style="width:100%;height:500px;"></div>-->
    <!--<div style="margin-top: 20px; text-align: right;width:100%;">-->
    <!--</div>-->
    <div class="title" :DetailData="DetailData">
      <div class="left " style="font-size: 24px"><span class="el-icon-edit-outline set"></span> <span class="titleCo">{{title}}</span></div>
      <div class="right" style="text-align: right;border-bottom: 0px;">
        <!--<el-button type="primary" size="small" class="sub" v-on:click="submits"> 保存 </el-button>-->
        <el-button   class="sub" size="small" v-on:click="xieru" style="margin-right: 20px;"> 返回 </el-button>
      </div>
      <div class="cleae" ></div>
    </div>
    <div class="">
      <el-form label-position="right" style="margin-right: 20px;" :label-width="languageData.id=='Chinese'?'100px':'150px'" :model="fromData" :rules="languageData.id=='Chinese'?rules:rules2" ref="fromData">
        <el-form-item label="类型:" v-show="!typeText" prop="type" style="max-width: 400px; text-align: left">
          <el-select  v-model="fromData.type" placeholder="请选择">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标题:" prop="title" style="max-width: 1000px">
          <el-input v-show="!typeText" v-model="fromData.title" type="text"></el-input>
          <p v-show="typeText" class="typeText">{{typeText}}</p>
        </el-form-item>
        <el-form-item label="简介:" prop="" v-show="!banner" style="height:600px;" >
          <quill-editor v-model="fromData.content" style="width:100%;height:500px;" ref="myTextEditor" :options="editorOption" @change="onChange">
            <div id="toolbar" slot="toolbar">
              <span class="ql-formats"><button type="button" class="ql-bold"></button></span>
              <span class="ql-formats"><button type="button" class="ql-italic"></button></span>
              <span class="ql-formats"><button type="button" class="ql-underline"></button></span>
              <span class="ql-formats"><button type="button" class="ql-strike"></button></span>
              <span class="ql-formats"><button type="button" class="ql-blockquote"></button></span>
              <span class="ql-formats"><button type="button" class="ql-code-block"></button></span>
              <span class="ql-formats"><button type="button" class="ql-header" value="1"></button></span>
              <span class="ql-formats"><button type="button" class="ql-header" value="2"></button></span>
              <span class="ql-formats"><button type="button" class="ql-list" value="ordered"></button></span>
              <span class="ql-formats"><button type="button" class="ql-list" value="bullet"></button></span>
              <span class="ql-formats"><button type="button" class="ql-script" value="sub"></button></span>
              <span class="ql-formats"><button type="button" class="ql-script" value="super"></button></span>
              <span class="ql-formats"><button type="button" class="ql-indent" value="-1"></button></span>
              <span class="ql-formats"><button type="button" class="ql-indent" value="+1"></button></span>
              <span class="ql-formats"> <button type="button" class="ql-direction" value="rtl"></button></span>
              <span class="ql-formats"><select class="ql-size">
        <option value="small"></option>
        <option selected></option>
        <option value="large"></option>
        <option value="huge"></option>
      </select></span>
              <span class="ql-formats"><select class="ql-header">
        <option value="1"></option>
        <option value="2"></option>
        <option value="3"></option>
        <option value="4"></option>
        <option value="5"></option>
        <option value="6"></option>
        <option selected="selected"></option>
      </select></span>
              <span class="ql-formats"><select class="ql-color">
        <option selected="selected"></option>
        <option value="#e60000"></option>
        <option value="#ff9900"></option>
        <option value="#ffff00"></option>
        <option value="#008a00"></option>
        <option value="#0066cc"></option>
        <option value="#9933ff"></option>
        <option value="#ffffff"></option>
        <option value="#facccc"></option>
        <option value="#ffebcc"></option>
        <option value="#ffffcc"></option>
        <option value="#cce8cc"></option>
        <option value="#cce0f5"></option>
        <option value="#ebd6ff"></option>
        <option value="#bbbbbb"></option>
        <option value="#f06666"></option>
        <option value="#ffc266"></option>
        <option value="#ffff66"></option>
        <option value="#66b966"></option>
        <option value="#66a3e0"></option>
        <option value="#c285ff"></option>
        <option value="#888888"></option>
        <option value="#a10000"></option>
        <option value="#b26b00"></option>
        <option value="#b2b200"></option>
        <option value="#006100"></option>
        <option value="#0047b2"></option>
        <option value="#6b24b2"></option>
        <option value="#444444"></option>
        <option value="#5c0000"></option>
        <option value="#663d00"></option>
        <option value="#666600"></option>
        <option value="#003700"></option>
        <option value="#002966"></option>
        <option value="#3d1466"></option>
      </select></span>
              <span class="ql-formats"> <select class="ql-background">
        <option value="#000000"></option>
        <option value="#e60000"></option>
        <option value="#ff9900"></option>
        <option value="#ffff00"></option>
        <option value="#008a00"></option>
        <option value="#0066cc"></option>
        <option value="#9933ff"></option>
        <option selected="selected"></option>
        <option value="#facccc"></option>
        <option value="#ffebcc"></option>
        <option value="#ffffcc"></option>
        <option value="#cce8cc"></option>
        <option value="#cce0f5"></option>
        <option value="#ebd6ff"></option>
        <option value="#bbbbbb"></option>
        <option value="#f06666"></option>
        <option value="#ffc266"></option>
        <option value="#ffff66"></option>
        <option value="#66b966"></option>
        <option value="#66a3e0"></option>
        <option value="#c285ff"></option>
        <option value="#888888"></option>
        <option value="#a10000"></option>
        <option value="#b26b00"></option>
        <option value="#b2b200"></option>
        <option value="#006100"></option>
        <option value="#0047b2"></option>
        <option value="#6b24b2"></option>
        <option value="#444444"></option>
        <option value="#5c0000"></option>
        <option value="#663d00"></option>
        <option value="#666600"></option>
        <option value="#003700"></option>
        <option value="#002966"></option>
        <option value="#3d1466"></option>
      </select></span>
              <span class="ql-formats"><select class="ql-font">
        <option selected="selected"></option>
        <option value="serif"></option>
        <option value="monospace"></option>
      </select></span>
              <span class="ql-formats">
        <select class="ql-align">
        <option selected="selected"></option>
        <option value="center"></option>
        <option value="right"></option>
        <option value="justify"></option>
      </select>
      </span>
              <span class="ql-formats">
          <button type="button" class="ql-clean"></button>
      </span>
              <span class="ql-formats">
          <button type="button" class="ql-link"></button>
      </span>
              <span class="ql-formats">
          <button type="button" @click="imgClick">
            <svg viewBox="0 0 18 18">
                <rect class="ql-stroke" height="10" width="12" x="3" y="4"></rect>
                <circle class="ql-fill" cx="6" cy="7" r="1"></circle>
                <polyline class="ql-even ql-fill" points="5 12 5 11 7 9 8 10 11 7 13 9 13 12 5 12"></polyline>
            </svg>
          </button>
      </span>
              <span class="ql-formats">
           <button type="button" class="ql-video"></button>
       </span>
            </div>
          </quill-editor>
          <cropupload v-model="showCrop" :width="width" :height="height" :fileName="fileName" :uploadUrl="uploadUrl" @uploadSuccess="onUploadSuccess"></cropupload>
        </el-form-item>
        <el-form-item label="轮播图片:" prop="" v-show="banner" style="text-align: left" >
          <el-upload :action="uploadUrl"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handlesuccess"
            :on-error="handleerror"
            :file-list="bannerlist"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible" size="tiny">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="">
          <div style="text-align: right;">
            <el-button @click="resetFields()">{{languageData.public.cancel}}</el-button>
            <el-button type="primary" @click="submitForm('fromData')">{{languageData.public.done}}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<style scoped="">
  .hello{;padding-top: 5px}
  .title{text-align: left;line-height: 52px;border-bottom: 1px solid #e1e1e1;margin-bottom: 10px; }
  .sub{cursor: pointer ;position: relative;top: -3px;}
  .set{margin-right: 10px;font-size: 24px;}
  .typeText{text-align: left; }
  .titleCo{font-size: 20px }
</style>
<script>
  // import '../../../static/utf8-jsp/ueditor.config'
  // import '../../../static/utf8-jsp/ueditor.all'
  // import '../../../static/utf8-jsp/lang/zh-cn/zh-cn'
  // import '../../../static/utf8-jsp/ueditor.parse'
  import cropupload from '../text/CropUpload'
  import { quillEditor } from 'vue-quill-editor'
  import Public from '@/vuex/public'
  import {mapState, mapActions} from 'vuex'
  export default {
    props: {
      /*编辑器的内容*/
      value: {
        type: String
      },
      /*上传图片的地址*/
      uploadUrl: {
        type: String
      },
      /*上传图片的file控件name*/
      fileName: {
        type: String
      },
      /*图片大小*/
      maxSize:{
        type:Number,
        default:400//kb
      },
      /*使用使用裁切*/
      canCrop:{
        type:Boolean,
        default:false
      },
      /*裁切的最小尺寸*/
      width:{
        type:Number,
        default:200
      },
      /*裁切的最小尺寸*/
      height:{
        type:Number,
        default:200
      }
    },
    created () {
      // 查看本页面路由 绑定对应页面class
      this.check = this.$route.name;
      var name = this.$route.query.id
      this.type = this.$route.query.id
      //新增 业务
      if(name == 'BusinessConfig'){
          this.id = parseInt(this.$route.query.bizId);
          this.title = '业务编辑 '
        this.options=[{label:'特殊业务', value: 1},{label:'普通业务', value: 0}]
        if(this.id){
          var parm = {id: this.id}
          this.showBizDetails(parm)
        }
      }
      //新增新闻
      if(name == 'nwes'){
        this.id = parseInt(this.$route.query.nwesId);
        this.title = '新闻编辑 '
        this.options=[{label:'公告', value: 2},{label:'普通新闻', value: 1}]
          if(this.id){
            var parm = {id: this.id}
            this.showNewsDetails(parm)
          }
      }
      //公司
      if(name == 'CompanyProfile'){
        //  头部
        this.id = parseInt(this.$route.query.page);
        this.title = this.id==0?'蓝湾简介': this.id==1?'公司理念':this.id==2?'我要合作':this.id==3?'首页banner':''
        // 隐藏多余 表单
        if(this.id==3){
          this.banner = true
        }
        this.typeText = this.title
        //初始化表单， 赋值，跳过表单验证
        this.fromData.title = 'this.typeText'
        var parm = { string:'string'}
        this.getIntroList(parm)
      }
      var usr = sessionStorage.getItem('user');
      if(usr) {
        usr = JSON.parse(usr);
        if(usr.type == 0){
          // this.$router.push({ name: 'AdminConfig' })
        }
      }else {
        if(this.check != 'login'){
          // this.$router.push({ name: 'AdminConfig' })
        }
      }
    },
    data () {
      return {
        bannerlist:[],
        list:[],
        dialogImageUrl: '',
        dialogVisible: false,
        banner:false,
        Public:Public,
        id: '',
        type:'',
        typeText:'',
        ue: '',
        uedata: [],
        xierudata: [],
        content: '',
        title: '',
        editorOption: {
          modules: {
            toolbar: '#toolbar'
          }
        },
        /*显示裁切控件*/
        showCrop:false,
        fromData:{
           type: 1,
           title:'',
           content:''
        },
        rules: {
          type: [
            { required: true, message: '请输选择类型', trigger: 'blur' },
          ],
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '类容不能为空', trigger: 'blur' },
          ],
        },
        rules2: {
          type: [
            { required: true, message: '请输选择类型', trigger: 'blur' },
          ],
          title: [
            { required: true, message: '请输入标题', trigger: 'blur' },
          ],
          content: [
            { required: true, message: '类容不能为空', trigger: 'blur' },
          ],
        },
        options:[{
          label:'公告',
          value: 0
        },{
          label:'普通新闻',
          value: 1
        }]
      }
    },
    computed: {
      editor() {
        return this.$refs.myTextEditor.quill;
      },
      initialize() {
        this.quill.on('text-change', (delta, oldDelta, source) => {
          let html = this.$refs.editor.children[0].innerHTML
        })
      },
      DetailData() {
        var parm = this.Detail
        if (parm) {
            this.dataFn(parm)
        }
       return 1
      },
      languageData: function () {
        var parm = this.language
        if (parm) {
          if (parm.check == 'Chinese') {
            parm = parm.Chinese
          }
          if (parm.check == 'English') {
            parm = parm.English
//            this.formConfig.labelWidth = '200px'
//            dom.style = 'width:620px'
          }
          // 替换 其他交互数据
//          this.updateDate(parm)
        }
        return parm
      },
      updateStatusData: function () {
        var parm = this.updateStatus
        if (parm) {
          this.listStatus(parm)
        }
        return 1
      },
      ...mapState([
        'Detail',
        'language',
        'updateList',
        'updateStatus'
      ])
    },
    components: {
      quillEditor,
      cropupload
    },
    mounted(){
      this.content = this.value;
      this.fromData={
        type: 1,
        title:'',
        content:''
      }
      if(this.type=='CompanyProfile'){
        this.fromData.title='sss'
      }
     // this.distFn()
    },
    watch: {
      'value'(newVal, oldVal) {
        if (this.editor) {
          if (newVal !== this.content) {
            this.content = newVal
          }
        }
      },
    },
    methods: {
      ...mapActions({
        delUser: 'delUserList',
        showBizDetails: 'showBizDetails',
        showNewsDetails: 'showNewsDetails',
        resetPassword: 'resetPassword',
        addNews: 'addNews',
        addBiz:'addBiz',
        getIntroList: 'Intro',
        updateIntro:'updateIntro',
        updateNewsStatus:'updateNewsStatus',
        updateBiz: 'updateBiz'
      }),
      handleRemove(file, fileList) {
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true;
      },
      handlesuccess(res,file,filelist){
        if(res.status == 0){
          // 替换请求成功img地址
          this.dialogImageUrl = res.data
          // filelist.push(file)
          // 替换file 本地img 地址
          file.url = res.data
          // 替换list图片的 本地img地址
          for (let i in filelist){
            if(file.uid == filelist[i].uid){
              filelist[i].url = file.url;

            }
          }
          // 暴露出来filelist，一遍上传地址
         this.list = filelist;
        }else {
          // 上传失败，文件路径清除
          file.url = null
          // 上传失败，文件列表路径清除
          for (let i in filelist){
            if(file.uid == filelist[i].uid){
              filelist.splice(i,1);
            }
          }
        }
      },
      handleerror(res){
      },
      submits(){

      },
      xieru(){
        this.$router.back(-1)
      },
      resetFields(){
        this.dialogFormVisible = false;
        this.$refs['fromData'].resetFields()
      },
      // 表单验证按钮
      submitForm (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if(this.type == 'nwes'){
              var parm = {
                title: this.fromData.title,
                type: this.fromData.type,
                content: this.fromData.content,
              }
               if(this.id){
                 parm.id= this.id
                 this.updateNewsStatus(parm)
               }else {
                 this.addNews(parm)
               }
            }
            if(this.type == 'BusinessConfig'){
              if(this.id){

                var parm = {
                  id:this.id,
                  bizName: this.fromData.title,
                  specialFlag: this.fromData.type,
                  bizIntro: this.fromData.content,
                }
                this.updateBiz(parm)
              }else {
                var parm = {
                  bizName: this.fromData.title,
                  specialFlag: this.fromData.type,
                  bizIntro: this.fromData.content,
                }
                this.addBiz(parm)
              }
            }
            if(this.type == 'CompanyProfile'){
              var parm = this.id==0?{intro:this.fromData.content }: this.id==1?{philo:this.fromData.content }:this.id==2?{cooper:this.fromData.content }:{homePics:[]}
              if(this.id == 3){
               for(let k in this.list){
                 parm.homePics.push(this.list[k].url)
               }
              }
              parm.id = this.commId
              this.updateIntro(parm)
            }
          } else {
            return false
          }
        })
      },
      // 操作是否成功
      listStatus (res) {
        if(res.code=='out'|| res.code=='outErorr'){
          return
        }
        if (res.status == 0) {
          // 修改成功
          var text = '';
          if(res.code == "addNews"){
            // 刷新列表
            text = this.languageData.id == 'Chinese'?'新闻添加成功':'create  successfully'
            this.openSuccess(text);
          }
          if(res.code == "addBiz"){
            // 刷新列表
            text = this.languageData.id == 'Chinese'?'业务添加成功':'create  successfully'
            this.openSuccess(text);
          }
          if(res.code == "updatNews"){
            // 刷新列表
            text = this.languageData.id == 'Chinese'?'新闻修改成功':'update  successfully'
            this.openSuccess(text);
          }
          if(res.code == "updateIntro"){
            // 刷新列表
            text = this.languageData.id == 'Chinese'?'公司信息修改成功':'update  successfully'
            this.openSuccess(text);
          }
          if(res.code == "updateBiz"){
            // 刷新列表
            text = this.languageData.id == 'Chinese'?'业务修改成功':'update  successfully'
            this.openSuccess(text);
          }
        }
        if (res.status != 0) {
          // 修改 修改失败
          var text = res.message
          if(res.code=="addNews"){
            text = this.languageData.id == 'Chinese'?'新闻添加失败':'news add failed'
          }
          if(res.code=="addBiz"){
            text = this.languageData.id == 'Chinese'?'业务添加失败':'news add failed'
          }
          if(res.code=="updateBiz"){
            text = this.languageData.id == 'Chinese'?'业务修改失败':'news add failed'
          }
          if(res.code=="updateIntro"){
            text = this.languageData.id == 'Chinese'?'公司信息修改失败':'news add failed'
          }
          if(res.code=="updatNews"){
            text = this.languageData.id == 'Chinese'?'新闻修改失败':'news add failed'
          }

          this.openError(text)
        }
        // 清空 vuex 中的本次记录，以免被下次操作状态造成混淆
        this.$store.commit('updateStatusTo', {body: null})
      },

      openSuccess (text) {
        this.$message({
          message: text,
          type: 'success'
        })
      },
      openError (text) {
        this.$message.error(text)
      },
      onChange(){
        this.$emit('input', this.content)
      },
      /*选择上传图片切换*/
      onFileChange(e){
        var fileInput = e.target;
       //;
        if (fileInput.files.length == 0) {
          return;
        }
        if (fileInput.files[0].size > 1024 * 1024 * this.maxSize) {
          alert('图片过大');
          return;
        }
        if (!this.uploadUrl) {
          return;
        }
        var self = this;
        var data = new FormData;
        data.append(this.fileName, fileInput.files[0]);
        this.editor.focus();
        var reader = new FileReader();
        // reader.readAsDataURL(fileInput.files[0]);
        // reader.onload = function ( event ) {
        //   var txt = event.target.result;
        //   console.log(txt)
        //   self.editor.insertEmbed(self.editor.getSelection().index, 'image', txt)
        // };
        self.$http.post(this.uploadUrl, data, { emulateJSON: true }).then(function (res) {
          self.editor.insertEmbed(self.editor.getSelection().index, 'image', res.body.data);
        }).catch(function (res) {

        })
      },
      /*裁切上传成功 res根据上传接口值获取*/
      onUploadSuccess:function (res) {
        this.editor.focus();
        this.editor.insertEmbed(this.editor.getSelection().index, 'image', res.url);
      },
      /*点击上传图片按钮*/
      imgClick() {
        if(this.canCrop){
          this.showCrop=true;
        }else{
          /*创建input file 不裁切，自己控制*/
          var input = document.createElement('input');
          input.type = 'file';
          input.name = this.fileName;
          input.accept = 'image/jpeg,image/png,image/jpg,image/gif';
          input.onchange = this.onFileChange;
          input.click();
        }
      },
      /*拉取详情*/
      distFn(){
        if(this.id){
          var parm = {
            id: this.id
          }
          this.showNewsDetails(parm)
        }
      },
      //详情解析
      dataFn(res){
         res=res.body.data
        if(this.type == 'BusinessConfig'){
          this.fromData={
            id:res.id,
            type: res.specialFlag,
            title:res.bizTypeName,
            content:res.bizIntro
          }
        }
        if(this.type == 'nwes'){
          this.fromData={
            id:res.id,
            type: res.type,
            title: res.title,
            content:res.content
          }
        }
        if(this.type == 'CompanyProfile'){
          this.commId = res.id
          this.fromData={
            type: 1,
            title: "公司",
            content:this.id==0?res.intro: this.id==1?res.philo:this.id==2?res.cooper:''
          }
          this.bannerlist = []
          for(let k in res.homePics){
            this.bannerlist.push({name:k,url:res.homePics[k]})
          }
          this.list = this.bannerlist
        }

      }
    }
  }
</script>

